﻿///<reference path="../Scripts/knockout-2.2.1.js" />
///<reference path="../Scripts/knockout.validation.js" />
///<reference path="../Scripts/jquery-1.9.1.intellisense.js" />
var asVM = "";
var ViewModelObject = {};
$(document).ready(function () {
    console.log("start");
    //////validation
    //url
    ko.validation.rules['url'] = {
        
        validator: function (val, validate) {
            return ko.validation.utils.isEmptyVal(val) || (
                validate && /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val)
            );
        },
        message: 'Похоже, что адрес сайта введён не верно.'
    };
    ko.validation.rules['requiredLogin'] = {
        validator: function (val, required) {
            var stringTrimRegEx = /^\s+|\s+$/g,
                testVal;

            if (val === undefined || val === null) {
                return !required;
            }

            testVal = val;
            if (typeof (val) == "string") {
                testVal = val.replace(stringTrimRegEx, '');
            }

            return required && (testVal + '').length > 0;
        },
        message: 'Что бы войти нужен логин, обязательно.'
    };
    ko.validation.rules['requiredPass'] = {
        validator: function (val, required) {
            var stringTrimRegEx = /^\s+|\s+$/g,
                testVal;

            if (val === undefined || val === null) {
                return !required;
            }

            testVal = val;
            if (typeof (val) == "string") {
                testVal = val.replace(stringTrimRegEx, '');
            }

            return required && (testVal + '').length > 0;
        },
        message: 'Без пароля хода нет, совсем.'
    };

    ko.validation.rules['equalPass'] = {
        validator: function (val, otherVal) {
            return val === otherVal;
        },
        message: 'Повторно введёный пароль не похож на предыдущий.'
    };
    console.log('minLength');
    /*ko.validation.rules['passMinLength'] = {
        validator: function (val, length) {
            return val.length >= length
        },
        message: 'Пароль должен содержать минимум ' + otherVal + 'симоволов.'
    };*/
    console.log('register Extenders');
    ko.validation.registerExtenders();

    /////////ViewModels
    //addSite
    function addSiteViewModel(url_, tags_, title_) {
        console.log('start addsiteViewModel');
        var self = this;
        //fields
        self.Url = ko.observable(url_).extend({ url: true });
        self.Tags = ko.observable(tags_);
        self.Title = ko.observable(title_);
        self.IsPrivate = ko.observable(false);
        self.errorMessage = ko.observable('');
        
        // comands
        self.submit = function () {
            if (self.Url.isValid()) {
                console.log("valid");
                $.post("/api/Bookmarks", {
                    __RequestVerificationToken: $(document.getElementsByName("__RequestVerificationToken")).val(),
                    Url: self.Url(),
                    Tags: self.Tags().split(" "),
                    Title: self.Title(),
                    isPrivate: self.IsPrivate
                }
                    , function (data) {
                        console.log(data);
                        if (data.status.toString() == "Ok") {
                            self.errorMessage('');
                            self.isOk(true);
                        }
                        else {
                            self.errorMessage('Что-то пошло не так, уже исправляем');
                        }
                    }, "json");
            }
            else {
                self.isError(true);
            }
        }
        self.StartEdit = function () {
            console.log('start edit');
            self.errorMessage('');
            self.isOk(false);

            self.SearchTtile = function () {
                if(self.Url.isValid())
                {
                    $.getJSON('/search/SearchTitle',{ url_: self.Url },
                        function (data) {
                            console.log(data);
                            if (data.status == 0)
                            {
                                self.Title(data.data);
                            }
                        })
                }
            }
        }

        //flags
        self.isError = ko.computed(function () { return (!self.Url.isValid() || self.errorMessage().length != 0) }, self);
        self.isOk = ko.observable(false);
        console.log('end addsiteViewModel');
    }

    //Login
    function loginFormViewModel() {
        console.log('start loginFormViewModel');
        var self = this;
        self.Login = ko.observable().extend({ requiredLogin: true });
        self.Password = ko.observable().extend({ requiredPass: true });
        self.errorMessage = ko.observable('');
        //flags
        self.isError = ko.computed(function () { return (!self.Login.isValid() || !self.Password.isValid()) || self.errorMessage().length > 0 });
        //comands
        self.StartEdit = function () {
            self.errorMessage('');
        }
        self.submit = function () {
            alert('submit');
            if (!self.isError) {
                console.log('submit');
            }
            else {
                console.log('submit but error');
                //document.getElementById('login-form').sumbit();
            }
        }
        console.log('end loginFormViewModel');
    }
    //registration
    function registerViewModel() {
        console.log('start registerViewModel');
        var self = this;
        self.UserName = ko.observable('');
        self.Password = ko.observable('')//.extend({ passMinLength: 5 });
        self.ConfirmPassword = ko.observable('').extend({ equalPass: self.Password() });

        self.errorMessage = ko.observable('');
        console.log('registerViewModel before isError');
        self.isError = ko.computed(function () {
            console.log('registerViewModel start isError');
            if (!self.ConfirmPassword.isValid() || self.errorMessage().length > 0  //|| !self.Password.isValid()
                ) {
                console.log('registerViewModel if true isError');
                return true;
            }
            console.log('registerViewModel if false isError');
            return false;
        });
        console.log('end registerViewModel');
    }

    //search
    function searchResult() {
        console.log('start searchResult');
        var self = this;
        self.Url = ko.observable('');
        self.HostUrl = ko.observable('');
        self.Favicon = ko.observable('');
        self.ImageUrl = ko.observable('');
        self.GeneralTitle = ko.observable('');
        self.Tags = ko.observableArray([]);
        self.Description = ko.observable('');

        console.log('end searchResult');
    };
    function tag(text, id, bookmark_id) {
        console.log('start tag');
        var self = this;
        self.Id = id;
        self.Text = text;
        console.log('end tag');
    } //в дальнейшем расширить для редактирования тегов
    function searchType(type, title) {
        var self = this;
        self.type = type;
        self.title = title;
    }

    function pageResult(pageNumber)
    {
        var self = this;
        self.Results = [];
        self.PageNumber = pageNumber;
    }

    function searchViewModel() {
        console.log('start searchViewModel');
        var self = this;
        console.log('searchViewModel start AllSearchTypes');
        //serach types 
        var general = new searchType('general', 'база TagThis.Org');
        var own = new searchType('own', 'мои закладки');
        self.AllSearchTypes = [own, general];
        console.log('searchViewModel start SearchType');
        self.SelectedSearchType = ko.observable(general);
        console.log('searchViewModel start SearchResults');
        self.SearchResults = ko.observableArray([]);
        self.isSearching = ko.observable(false);
        self.InputTagText = ko.observable("");
        self.ResultPerPage = ko.observable(10);
        self.PagesCount = ko.observable(0);
        self.CurrentPage = ko.observable(1);



        self.InputTagText.subscribe(function () {
            var rawTags = self.InputTagText();
            if (rawTags.length > 1) {
                console.log("trying to wrap");
                var tagsToWrap = rawTags.split(tagSeparator)
                if (tagsToWrap.length > 1) {
                    $.each(tagsToWrap, function (i, v) {
                        $('#tags').tagit('createTag', v);
                    });
                    self.InputTagText("");
                }
            }
        });

        console.log('searchViewModel start TagsForSearch');
        self.TagsForSearch = function () {
            var tagsObs = [];
            $.each($('#tags > .tagit-choice > span'), function (k, val) {
                tagsObs.push(val.textContent);
            });
            return tagsObs;
        };

        console.log('searchViewModel start SelectTypes');

        self.SelectType = function (type) {
            if (self.SelectedSearchType() != type) {
                self.SelectedSearchType(type);
                if (!self.TagsForSearch().length == 0) {
                    self.Search();
                }
            }

        };
        self.Search = function () {
            console.log("searching in " + self.SelectedSearchType().type);
            self.isSearching(true);
            if (self.TagsForSearch().length > 0) {
                //console.log(self.TagsForSearch())
                var allTags = self.TagsForSearch()
                $.ajax(
                    '/Search/Search',
                    {
                        type: "POST",
                        dataType: "json",
                        traditional: true,
                        data: {
                            tags: allTags,
                            needCount: self.PagesCount() > 0 ? false : true,
                            currentPage: self.CurrentPage(),
                            resultPerPage : self.ResultPerPage()
                        },
                        success: function (data) {
                            console.log(data)
                            // console.log(data);
                            //$.each(data, function (k, v) {
                            //    var sr = new searchResult();
                            //    sr.Url(v.Url);
                            //    sr.GeneralTitle(v.GeneralTitle);
                            //    sr.Favicon(v.Favicon);
                            //    sr.ImageUrl(v.ImageUrl);
                            //    sr.Description(v.Description);
                            //    sr.Tags($.map(v.Tags, function (va) { var t = new tag(va.Text, va.Id, 0); return t; }));
                            //    self.SearchResults.push(sr);
                            //    console.log("add");
                            //});
                            //var item = $('.search-result .search-result-item');
                            //item.filter(":even").wrapAll('<div class="col left">');
                            //item.filter(":odd").wrapAll('<div class="col right">');
                        },
                        error: function (obj, status, smth) {
                            console.log('error' + obj + ' ' + status)
                        }//,
                        //.. complete: function (obj, status) { console.log('complete' + obj + ' ' + status) }
                    })
                //$.post('/Search/Search', {  }, function (data) {
                //    $.each(data, function (k, v) {
                //        var sr = new searchResult();
                //        sr.Url(v.Url);
                //        sr.GeneralTitle(v.GeneralTitle);
                //        sr.Favicon(v.Favicon);
                //        sr.ImageUrl(v.ImageUrl);
                //        sr.Description(v.Description);
                //        sr.Tags($.map(v.Tags, function (va) { var t = new tag(va.Text, va.Id, 0); return t; }));
                //        self.SearchResults.push(sr);
                //        console.log("add");
                //    });
                //    var item = $('.search-result .search-result-item');
                //    item.filter(":even").wrapAll('<div class="col left">');
                //    item.filter(":odd").wrapAll('<div class="col right">');
                //}, "json");


                //$.getJSON('/Search/Search', { 'tags': allTags }, function (data) {
                //    $.each(data, function (k, v) {
                //        var sr = new searchResult();
                //        sr.Url(v.Url);
                //        sr.GeneralTitle(v.GeneralTitle);
                //        sr.Favicon(v.Favicon);
                //        sr.ImageUrl(v.ImageUrl);
                //        sr.Description(v.Description);
                //        sr.Tags($.map(v.Tags, function (va) { var t = new tag(va.Text, va.Id, 0); return t; }));
                //        self.SearchResults.push(sr);
                //        console.log("add");
                //    });
                //    var item = $('.search-result .search-result-item');
                //    item.filter(":even").wrapAll('<div class="col left">');
                //    item.filter(":odd").wrapAll('<div class="col right">');
                //}
                //);


            }
        };
        //self.Scroled = function(data, event) {
        //    var elem = event.target;
        //    if (elem.scrollTop > (elem.scrollHeight - elem.offsetHeight - 200)) {
        //        //getItems(20);
        //        console.log("request");
        //    }
            console.log('end searchViewModel');
        }
        console.log('ViewModelObject');
        ViewModelObject = {
            asVM: new addSiteViewModel(),
            lVM: new loginFormViewModel(),
            rVM: new registerViewModel(),
            sVM: new searchViewModel()
        }
        //  lVM = new loginFormViewModel();
        console.log('ko.applyBindings');
        ko.applyBindings(ViewModelObject);
        // ko.applyBindings(lVM, document.getElementById('login-from'));
        //console.log(tagSeparator);
        console.log('Ok');
    });


